package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.BooleanQuery;
import org.checkerframework.checker.units.qual.A;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thread.AppThreadLocalUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * es分页检索
     *
     * @param dto
     * @return
     * @throws IOException
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1.参数校验
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return null;
        }
        //异步调用 保存搜索记录
        ApUser apUser = AppThreadLocalUtil.getApUser();
        if (apUser != null && dto.getFromIndex() == 0) {
            apUserSearchService.insert(dto.getSearchWords(), apUser.getId());
        }
        //2.数据处理
        SearchRequest request = new SearchRequest("app_info_article");
        //多条件查询,bool构建
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键字分词
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", dto.getSearchWords())).should(QueryBuilders.matchQuery("content", dto.getSearchWords()));
        //查询小于mindate的
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime().getTime()));
        request.source().query(boolQueryBuilder);
        //执行分页
        request.source().from(0).size(dto.getPageSize());
        //按照发布时间倒序
        request.source().sort("publishTime", SortOrder.DESC);
        //设置高亮
        request.source().highlighter(new HighlightBuilder().field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>"));
        //发送查询请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //3.结果封装返回
        List<Map> list = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String jsonString = hit.getSourceAsString();
            Map map = JSON.parseObject(jsonString, Map.class);
            //处理高亮
            if (hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0) {
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                map.put("h_title", title);
            } else {
                //source中的title
                map.put("h_title", map.get("title"));
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
